pass # Force Zope to debug line numbers correctly


##############################################################################################
#
#    FIXME - Hacked togethor from snippets of similar parts of KE. 
#    needs a lot of cleaning up.
#    (The entire assessmentexplorer needs rewriting)
# 
##############################################################################################



from Products.KnowledgeEngine.KERLProcessor import parseKERL

#set the default batch size (number of users to display at once)
batchSize = 15

#get the request from the context... we will use it to find stuff!
request=context.REQUEST
form = request.form

#get the sercurity, user provider, assessment storage and credit management services
securityService = context.knowledgeengine_securityservice
userProviderService = context.knowledgeengine_userproviderservice
assessmentStorageService = context.knowledgeengine_assessmentstorageservice
creditManagementService = context.knowledgeengine_creditmanagementservice

#get the knowledge engine user
user = userProviderService.getUser(request["AUTHENTICATED_USER"].getId())


#set the report information in the request

if not hasattr( assessmentStorageService, 'getSearchIndices' ):
    raise "Search Indexes are not supported by this assessment storage service"

indices = []

from Products.KnowledgeEngine.AssessmentFilter import AssessmentFilter, decodeAssessmentFilterFromString


search = context.REQUEST.get('search',{})
kerl   = context.REQUEST.get('kerl', None)

anyOrAll = context.REQUEST.get('anyOrAll','all')

searchmode = form.get('searchmode',None)
if form.has_key('search-kerl'):
    searchmode='kerl'
elif form.has_key('search-form'):
    searchmode='form'


if searchmode == 'kerl':    
    q = parseKERL(kerl)
elif searchmode == 'form':
    q =  [anyOrAll]
    for key, value in search.items():
        if key and value:
            q.append( [("idx:%s" % key), "LIKE", value] )
            
    q = ['all', q]            
            
    createdby = form.get('createdby',False)
    
    if createdby:
        action = 'createdby'
        createdbytype = form.get('createdby-type')
        if createdbytype == 'group':
            q.append( ['assessment','createdbygroup',createdby] )      
        else:
            q.append( ['assessment','createdby',createdby] )      
        
    createdbefore = form.get('createdbefore',False)
    if createdbefore:
        q.append( ['assessment','createdbefore',createdbefore] )      
        
    createdafter = form.get('createdafter',False)
    if createdafter:
        q.append( ['assessment','createdafter',createdafter] )              
                
                
              
    checkedout = form.get('checkedout',False)
    if checkedout == 'Y':
        q.append( ['assessment','ischeckedout'] )
    elif checkedout == 'N':
        q.append( ['assessment','isnotcheckedout'] )        


else:
    q = None
    

modelIdentities = filter(None,form.get('modelIdentities',''))
if modelIdentities:
    models = securityService.getModelsByIdentity( modelIdentities )
else:
    models = filter(None,[b.getObject() for b in context.portal_catalog(portal_type='Model')])


reportsByModel = {}
for model in models:
    if not model.getIdentity() in reportsByModel:
        reportsByModel[model.getIdentity()] = model.getReports()
        
    modelReports = model.getReports(user, 'SingleAssessmentReport')
    



if q:
    assessmentFilter = AssessmentFilter( "Test", q, models, '*' )
    assessments = assessmentStorageService.getAssessmentsSatisfyingFilter( assessmentFilter, user )
else:
    assessments = []    


for index in assessmentStorageService.getSearchIndices(onlyPopulated=True):
    brain = {'searchIndex': index[0], 
             'valueType'  : index[1],
             'numValues'  : index[2],
            }
                
    indices.append( brain )                    

model = models[0]

batchNr = int(request.get('page', 1)) - 1   

batch = assessments[batchNr * batchSize: (batchNr + 1) * batchSize]
nrAssessments = len(assessments)
nrBatches = nrAssessments / batchSize

if   request.has_key('btnNext') : batchNr+=1
elif request.has_key('btnBack') : batchNr-=1
elif request.has_key('btnFirst'): batchNr=0
elif request.has_key('btnLast') : batchNr=nrBatches

elif request.form.has_key('btnDeleteAssessments') or request.form.has_key('btnLockAssessments') or request.form.has_key('btnUnlockAssessments') or request.form.has_key('btnRenameAssessments'):
    #build a list of the selected assessments
    
    assessmentIds = []
    prefix = "chkAssessment"
    for formKey in request.form.keys():
        if prefix == formKey[0:len(prefix)]:
            assessmentId = formKey[len(prefix):]
            assessmentIds += [assessmentId]
    assessments = [assessmentStorageService.loadAssessment(assessmentId, model) for assessmentId in assessmentIds]

    if request.form.has_key('btnRenameAssessments'):
        #------------------------------------#
        # RENAME ASSESSMENT(s)

        #get permission
        renameAnyAssessmentPermission = securityService.getEffectivePermission('RenameAnyAssessment', model.getIdentity(), user.getIdentity());

        #does the user have permission to rename assessment(s)?
        if renameAnyAssessmentPermission is not None and renameAnyAssessmentPermission.granted():

            #build a list of the assessment to be renamed
            assessmentIds = []
            prefix = "txt%s" % (model.getIdentity(),)
            for formKey in request.form.keys():
                if prefix == formKey[0:len(prefix)]:
                    assessmentId = formKey[len(prefix):]
                    originalName = request.form['hid%s%s' % (model.getIdentity(), assessmentId)]
                    newName = request.form['txt%s%s' % (model.getIdentity(), assessmentId)]
                    if originalName != newName:
                        assessmentIds += [assessmentId]
                assessments = [assessmentStorageService.loadAssessment(assessmentId, model) for assessmentId in assessmentIds]

                #rename each of the assessments
                for assessment in assessments:
                    #set the new name for the assessment
                    assessment.setName(request.form['txt%s%s' % (model.getIdentity(), assessment.getIdentity())])

                    #now save the actual assessment
                    assessmentStorageService.saveAssessment(assessment)

    if request.form.has_key('btnDeleteAssessments'):
        #------------------------------------#
        # DELETE ASSESSMENT(s)

        #get permission
        deleteAnyAssessmentPermission = securityService.getEffectivePermission("DeleteAnyAssessment", model.getIdentity(), user.getIdentity())

        #does the user have permission to delete assessment(s)?
        if deleteAnyAssessmentPermission is not None and deleteAnyAssessmentPermission.granted():

            #do we need to refund credits for assessment deletion?
            refundPermission = securityService.getEffectivePermission("RefundCreditsForAssessmentDeletion", model.getIdentity(), user.getIdentity())

            #delete each of the assessments
            deletionCount = 0
            for assessment in assessments:
                #handle the 'onBeforeDeleteAssessment' event for the model
                if model.isEventEnabled("onBeforeDeleteAssessment"):
                    model.getEnabledEvent("onBeforeDeleteAssessment").execute(assessment, user)

                #delete the actual assessment
                assessmentStorageService.deleteAssessment(assessment)

                #refund the credit?
                if refundPermission is not None and refundPermission.granted():            
                    
                    #get the credit transaction that was used to create the assessment (we will reverse that transaction)
                    creditTxn = assessment.getCreditTransactionIdentity()
                    
                    #if we have one... let's reverse it
                    if creditTxn is not None and len(creditTxn) > 0:
                        creditManagementService.reverseCredits(creditTxn, user.getIdentity(), "Refund for deleted assessment [%s]" % assessment.getName())

    if request.form.has_key('btnLockAssessments') or request.form.has_key('btnUnlockAssessments'):
        #------------------------------------#
        # UN/LOCK ASSESSMENT(s)

        #get permission
        changeAnyAssessmentLockStatePermission = securityService.getEffectivePermission('ChangeAnyAssessmentLockState', model.getIdentity(), user.getIdentity());

        #does the user have permission to lock/unlock assessment(s)?
        if changeAnyAssessmentLockStatePermission is not None and changeAnyAssessmentLockStatePermission.granted():
        
            #locking or unlocking?
            locking = request.form.has_key('btnLockAssessments')
            #lock/unlock the selected assessments
            for assessment in assessments:                 
                #lock it?
                if locking and not assessment.getIsLocked():
                    #handle the 'onBeforeLockAssessmentInAnyRepository' event for the model
                    if model.isEventEnabled("onBeforeLockAssessmentInAnyRepository"):
                        model.getEnabledEvent("onBeforeLockAssessmentInAnyRepository").execute(assessment, user)
                
                    #lock
                    assessment.setIsLocked(locking)                               
                
                if not locking and assessment.getIsLocked():                    
                    #unlock
                    
                    assessment.setIsLocked(locking)

                #save the assessment
                assessmentStorageService.saveAssessment(assessment)

elif request.form.has_key('page'):
    #direct page navigation
    batchNr = int(request.form['page']) - 1

else:
    #we've come from another page or refreshing
    pass



options = {
    'indices':      indices, 
    'assessments':  batch,
    'model':        model, 
    'reportsByModel': reportsByModel,
    'kerl': q,
    'nrAssessments': nrAssessments,
    'batchNr': batchNr,
    'nrBatches': nrBatches,
    'searchmode': searchmode,
    
}   


return context.assessmentexplorer_bysearchindex_render(**options)




